import { postLoginMbApi, postLoginTokenApi } from "@/api/login";
import { postSmsLoginApi } from "@/api/sms";

export default {
  namespaced: true,
  state: {
    uname: localStorage.getItem("uname") || "",
    roleName: localStorage.getItem("roleName") || "",
    token: localStorage.getItem("token") || "",
  },
  getters: {},
  mutations: {
    setUserinfo(state, payload) {
      state.uname = payload.uname;
      state.roleName = payload.roleName;
      state.token = payload.token;
    },
    deleteUserinfo(state) {
      state.uname = "";
      state.roleName = "";
      state.token = "";

      localStorage.clear();
    },
  },
  actions: {
    async FETCH_MB_LOGIN(context, payload) {
      const res = await postLoginMbApi(payload);
      if (res.meta.state === 200) {
        // H5存储
        localStorage.setItem("uname", res.data.uname);
        localStorage.setItem("roleName", res.data.roleName);
        localStorage.setItem("token", res.data.token);
        // 触发mutations保存
        context.commit("setUserinfo", res.data);
      }
      // 思考：为啥要返回res
      // 回答：仓库层仅仅做存储逻辑，只有提示跳转还是在视图层操作
      return res;
    },
    async FETCH_SMS_LOGIN(context, payload) {
      const res = await postSmsLoginApi(payload);
      if (res.meta.state === 200) {
        // H5存储
        localStorage.setItem("uname", res.data.uname);
        localStorage.setItem("roleName", res.data.roleName);
        localStorage.setItem("token", res.data.token);
        // 触发mutations保存
        context.commit("setUserinfo", res.data);
      }
      // 思考：为啥要返回res
      // 回答：仓库层仅仅做存储逻辑，只有提示跳转还是在视图层操作
      return res;
    },
    async FETCH_TOKEN_LOGIN(context, payload) {
      const res = await postLoginTokenApi(payload);
      if (res.meta.state === 200) {
        // H5存储
        localStorage.setItem("uname", res.data.uname);
        localStorage.setItem("roleName", res.data.roleName);
        localStorage.setItem("token", res.data.token);
        // 触发mutations保存
        context.commit("setUserinfo", res.data);
      }
      // 思考：为啥要返回res
      // 回答：仓库层仅仅做存储逻辑，只有提示跳转还是在视图层操作
      return res;
    },
  },
};
